import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { isHttp, isEmpty } from "@/utils/validate"
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/static/images/profile.jpg'

const baseUrl = config.baseUrl
// 本地用户资料缓存键与有效期（毫秒）
const USER_CACHE_KEY = 'user:profile'
const USER_CACHE_TTL = 10 * 60 * 1000 // 10分钟

const user = {
  state: {
    token: getToken() || '',
    id: storage.get(constant.id),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions)
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
      storage.set(constant.id, id)
    },
    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
	  const loginType = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password,loginType, code, uuid).then(res => {
          setToken(res.data.access_token)
          commit('SET_TOKEN', res.data.access_token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }, payload = {}) {
      console.log('GetInfo action中当前token:', state.token)
      const forceRefresh = !!(payload && payload.forceRefresh)
      return new Promise((resolve, reject) => {
        try {
          if (!forceRefresh) {
            const cache = uni.getStorageSync(USER_CACHE_KEY)
            if (cache && cache.ts && (Date.now() - cache.ts) < USER_CACHE_TTL && cache.data) {
              const user = cache.data
              // 还原并提交缓存中的字段
              const userid = user.Id || user.id || ''
              const username = user.patientName || user.nickName || user.username || ''
              let avatar = cache.avatar || user.avatar || ''
              if (!isHttp(avatar)) {
                avatar = (isEmpty(avatar)) ? defAva : baseUrl + avatar
              }
              // 兼容微信小程序头像强缓存
              // #ifdef MP-WEIXIN
              if (isHttp(avatar)) {
                const sep = avatar.indexOf('?') >= 0 ? '&' : '?'
                avatar = `${avatar}${sep}_t=${Date.now()}`
              }
              // #endif
              commit('SET_ID', userid)
              commit('SET_NAME', username)
              commit('SET_AVATAR', avatar)
              commit('SET_ROLES', cache.roles || [])
              commit('SET_PERMISSIONS', cache.permissions || [])
              return resolve({ data: user, fromCache: true })
            }
          }
        } catch (e) { /* 忽略缓存读取异常，降级继续请求 */ }

        getInfo().then(res => {
          const user = res.data
          let avatar = user.avatar || ""
          if (!isHttp(avatar)) {
            avatar = (isEmpty(avatar)) ? defAva : baseUrl + avatar
          }
          // 小程序端强缓存规避：为 http(s) 头像追加时间戳参数（仅 MP-WEIXIN 生效）
          // #ifdef MP-WEIXIN
          if (isHttp(avatar)) {
            const sep = avatar.indexOf('?') >= 0 ? '&' : '?'
            avatar = `${avatar}${sep}_t=${Date.now()}`
          }
          // #endif
          const userid = (isEmpty(user) || isEmpty(user.Id)) ? "" : user.Id
          const username = (isEmpty(user) || isEmpty(user.patientName)) ? "" : user.patientName
          // 兼容后端未返回角色权限的情况
          if (res && res.data && Array.isArray(res.data.roles) && res.data.roles.length > 0) {
            commit('SET_ROLES', res.data.roles)
            commit('SET_PERMISSIONS', res.data.permissions || [])
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
            commit('SET_PERMISSIONS', [])
          }
          commit('SET_ID', userid)
          commit('SET_NAME', username)
          commit('SET_AVATAR', avatar)
          // 写入缓存：原始 user、派生头像与权限
          try {
            uni.setStorageSync(USER_CACHE_KEY, {
              ts: Date.now(),
              data: user,
              avatar,
              roles: (res && res.data && res.data.roles) || ['ROLE_DEFAULT'],
              permissions: (res && res.data && res.data.permissions) || []
            })
          } catch (e) { /* 忽略写入异常 */ }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          storage.clean()
          try { uni.removeStorageSync(USER_CACHE_KEY) } catch (e) {}
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
